package com.bite.order.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

@Component
public class SentinelExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException e) throws Exception {
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();

        int status = 429;
        String msg = "Blocked by Sentinel (flow limiting)";

        if (e instanceof AuthorityException) {
            status = 401;
            msg = "授权失败, 请联系服务端进行配置";
        }else if(e instanceof DegradeException){
            msg = "触发降级规则, 请联系服务端进行配置";
        }else if(e instanceof FlowException){
            msg = "触发限流规则, 请联系服务端进行配置";
        }else if(e instanceof ParamFlowException){
            msg = "触发热点限流规则, 请联系服务端进行配置";
        }

        response.setStatus(status);
        out.print(msg);
        out.flush();
        out.close();
    }
}
